package com.roc.web.action.estrn;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.RiskYsbEstrnInfoBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.file.DeleteDir;
import com.roc.util.file.Jbigtobmp;
import com.roc.util.httpZip.HttpFileToZipUtil;

@Component
@Scope("prototype")
@Namespace("/riskYsbEstrn")
public class RiskYsbEstrnInfoAction extends PaginationBaseAction{

	private static final long serialVersionUID = -4049588019525630037L;

	private Logger logger=LogManager.getLogger(RiskYsbEstrnInfoAction.class);
	
	private RiskYsbEstrnInfoSearchCondition searchCondition;
	
	private InputStream excelFile;
	@Autowired
	IPageService pagenitionService;
	
	@Autowired
	IExcelService excelService;
	
	String FilePath = Utils.getConfigValue("CADES_IMAGE_PATH");
	
	protected Map<String,String> respondeMap = ConfigProperties.getSysDB1("RESP_CD",false);
	protected Map<String,String> reversalMap=ConfigProperties.getReversalTypes();
	protected Map<String,String> tranMap = ConfigProperties.getSysDB1("TRANS_CD",false);
	
	
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/estrn/riskQueryYsbEstrn.jsp")
				,@Result(name = "error", location = "/error.jsp")})
	public String queryEstrnHisInfoAction() throws Exception{
		logger.info("跳转到云商宝交易风控查询页面");
        Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
        if (!op.getRoleType().equals(Role.SYSTEM.getCode()) && !op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
        		&& !op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
        
        if(searchCondition==null){
			searchCondition=new RiskYsbEstrnInfoSearchCondition();
		}
		
		searchCondition.setMinDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
		searchCondition.setMaxDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
	    org();
		return SUCCESS;
	}
	
	
	
	
	@Action(value = "queryRiskEstrnList", results = { @Result(name = "success", location = "/pages/estrn/riskQueryYsbEstrn.jsp")
           })
	//查询云商宝交易记录
	public String queryEstrnHisListAction() throws Exception{

		logger.info("风控人员查询云商宝交易记录");
        Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(searchCondition==null){
				searchCondition=(RiskYsbEstrnInfoSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new RiskYsbEstrnInfoSearchCondition();
				}
			}
			logger.info("查询条件："+"交易日期："+searchCondition.getMinDate()+"-"+searchCondition.getMaxDate());
			if("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate())) || "".equals(Constance.Null2EmptyTrim(searchCondition.getMaxDate()))){
				logger.info("云商宝交易查询查询条件时间为空");
				return SUCCESS;
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<RiskYsbEstrnInfoBean> tftList = new ArrayList<RiskYsbEstrnInfoBean>();
			dealTheSearchRsList(tftList,searchRsList,true);
		
			getRequest().setAttribute("tftList", tftList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			org();
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
			
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		// 查询完毕后删除电子签名文件夹中文件信息
		DeleteDir.deleteDir(FilePath);
//		HttpFileToZipUtil.deletefile(path);
		
		return SUCCESS;
	}
	
	/**
	 * 导出风控云商宝交易信息
	 * @Title: exportRiskysbEstrnInfo
	 * @return
	 * @throws Exception
	 * @author JD
	 * @date: 2018年4月16日 
	 *
	 */
	@Action(value="exportRiskysbEstrnInfo",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/estrn/riskQueryYsbEstrn.jsp") }) 
	public String  exportRiskysbEstrnInfo() throws Exception{
		logger.info("导出云商宝交易明细-风控角色");
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		if (searchCondition == null) {
			searchCondition = (RiskYsbEstrnInfoSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new RiskYsbEstrnInfoSearchCondition();
			}
		}
		if ("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate()))) {
			logger.info("云商宝历史交易导出导出条件为空");
			return "error";
		}
		try {
			
			int rows = pagenitionService.countSQL(searchCondition);
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,calcuStart(getCurrentPage()), rows);
			}
			List<RiskYsbEstrnInfoBean> tftList = new ArrayList<RiskYsbEstrnInfoBean>();
			dealTheSearchRsList(tftList,searchRsList,false);

			SXSSFWorkbook work = excelService.exportRiskYsbHisTransFlow(tftList,
					searchCondition.getMinDate(), searchCondition.getMaxDate(),
					logingMerchant.getRoleType());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());

		}

		return SUCCESS;
	}
	
	
	private void dealTheSearchRsList(List<RiskYsbEstrnInfoBean> tftList,
			List<Object> searchRsList , boolean status) {
		try {
			
	    Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	    
		if(searchRsList!=null&&searchRsList.size()>0){
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				RiskYsbEstrnInfoBean t = new RiskYsbEstrnInfoBean();
				
		        t.setMobileNo(Constance.Null2EmptyTrim(obj[0]));
		        t.setMchntCdConv(Constance.Null2EmptyTrim(obj[1]));
		        t.setUnTermCd(Constance.Null2EmptyTrim(obj[2]));
		        t.setPriAcctNo(Constance.Null2EmptyTrim(obj[3]));
		        
		        String posEntrymd = Constance.Null2EmptyTrim(obj[4]);
		        String cardClass = Constance.Null2EmptyTrim(obj[10]);
				t.setPosEntryMdCd(posEntrymd);
				if(posEntrymd.length()<3){
					t.setPosEntryMdCdName("未知");
				}else if("02".equals(posEntrymd.substring(0, 2))){
					t.setPosEntryMdCdName("磁条卡");
				}else if("05".equals(posEntrymd.substring(0, 2))){
					t.setPosEntryMdCdName("芯片插卡");
				}else if("07".equals(posEntrymd.substring(0, 2))){
					if("".equals(cardClass)){
						t.setPosEntryMdCdName("未知");
					}else if("0".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片非接");
					}else if("1".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片云闪付");
					}
				}else if("98".equals(posEntrymd.substring(0, 2))){
					if("".equals(cardClass)){
						t.setPosEntryMdCdName("未知");
					}else if("0".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片非接");
					}else if("1".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片云闪付");
					}
				}
		        t.setTransDt(Constance.Null2EmptyTrim(obj[5]));
		        t.setTransMt(Constance.Null2EmptyTrim(obj[6]));
		        t.setMaTransSeq(Constance.Null2EmptyTrim(obj[7]));
		        t.setRetriRefNoConv(Constance.Null2EmptyTrim(obj[8]));
		        t.setRespCd(Constance.Null2EmptyTrim(obj[9]));
				t.setRespName(respondeMap.get(Constance.Null2EmptyTrim(obj[9])));
				t.setCertifId(Constance.Null2EmptyTrim(obj[11]));
				if(status) {
					String data =Constance.Null2EmptyTrim(obj[12]);
//					Jbigtobmp.createImg(data, "X:\\imgSave\\img\\5\\"+t.getRetriRefNoConv());
//					String imgFile="X:\\imgSave\\img\\5\\"+t.getRetriRefNoConv()+".bmp";
					Jbigtobmp.createImg(data, FilePath+t.getRetriRefNoConv());
					String imgFile=FilePath+t.getRetriRefNoConv()+".bmp";
					File file = new File(imgFile);
					if(file.exists()) {
						String base64data=Jbigtobmp.getImageStr(imgFile);
						t.setSignPicture(base64data);
					}
				}
				
				tftList.add(t);
			}
		}
		} catch (Exception e) {
			logger.error("风控云商宝交易查询List解析异常：",e);
			throw new RuntimeException("风控云商宝交易查询List解析异常");
		}
		
	}
	
	
	public void org(){
		HashMap<String , String> newResMap = new LinkedHashMap<String, String>();
		
		Set<Entry<String,String>> entrySet = respondeMap.entrySet();
		Iterator it = entrySet.iterator();
		while(it.hasNext()){
			Entry<String,String> en = (Entry<String, String>) it.next();
			String key = en.getKey();
			String value = en.getValue();
			if(!"00".equals(key)){
				newResMap.put(key, value);
			}else{
				newResMap.put(key, value);
				newResMap.put("9999", "失败");
			}
		}
		
		getRequest().setAttribute("tranMap",tranMap);
		getRequest().setAttribute("respMap",newResMap);
	}
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (RiskYsbEstrnInfoSearchCondition)getSession().getAttribute(RISK_YSB_SEARCH_SESSION_BEAN_ESTRN);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(RISK_YSB_SEARCH_SESSION_BEAN_ESTRN, searchCondition);
	}

	public RiskYsbEstrnInfoSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(RiskYsbEstrnInfoSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}




	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	public IExcelService getExcelService() {
		return excelService;
	}
	public void setExcelService(IExcelService excelService) {
		this.excelService = excelService;
	}

	
	public String getExcelName() {
		String excelName="云商宝交易信息查询-风控角色"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	



}
